//
//  GJEmoManage.m
//  GJKeyboard
//
//  Created by Jerry_hqyj on 2017/11/22.
//  Copyright © 2017年 socket. All rights reserved.
//

#import "GJEmoManage.h"

static NSMutableArray *emotionArray;
@implementation GJEmoManage

+ (NSMutableDictionary *)emotionManage:(NSString *)plistPath plistType:(NSInteger)type itemCount:(int)count
{

    NSMutableDictionary *emoDic = [self dictionaryWithPlistPath:plistPath plistType:type  withItemCount:count];
    return emoDic;

}

+ (NSMutableDictionary *)dictionaryWithPlistPath:(NSString *)plist plistType:(NSUInteger)plistType withItemCount:(int)count
{
    //存放每组表情和每组表情的页码数的字典
    NSMutableDictionary *emotionDic = [NSMutableDictionary dictionary];
    
    //存放从plist中获取到的表情，用来进行升序排序
    NSMutableArray *emoArray = [NSMutableArray array];
    NSMutableArray *sysEmoArr = [NSMutableArray array];
    
    //对应的key值
    NSMutableArray *emoKeyArray = [NSMutableArray array];
    NSMutableArray *sysKeyEmoArr = [NSMutableArray array];
    
    
    NSString *path = [[NSBundle mainBundle] pathForResource:plist ofType:nil];
    
    NSArray *array;
    
    if (plistType == NSDictionaryType) {
        
        NSDictionary *emoDic = [NSDictionary dictionaryWithContentsOfFile:path];
        
        for (NSString *key in [emoDic allKeys]) {
            
            [emoKeyArray addObject:key];
            
            NSString *value = emoDic[key];
            [emoArray addObject:value];
        }
        
        //升序
        NSArray *result = [emoArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
            
            return [obj1 compare:obj2];
            
        }];
        array = result;
        //        NSLog(@"result-------- %@", emoDic);
        [sysEmoArr setArray:array];
        
        for (int index = 0; index < result.count; index++) {
            NSString *object = result[index];
            [emoDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                
                if ([obj isEqual:object])
                {
                    [sysKeyEmoArr addObject:key];
                
                }
            }];
        }
         
        [sysKeyEmoArr setArray:sysKeyEmoArr];
    }
    else if (plistType == NSArrayType) {
        
        NSArray *emoArray = [NSArray arrayWithContentsOfFile:path];
        array = emoArray;
        //        sysEmoArr = [NSMutableArray arrayWithArray:emoArray];
        [sysEmoArr setArray:array];
        [sysKeyEmoArr setArray:emoArray];
    }
    
    //     NSLog(@"sysEmoArr------ %@", sysEmoArr);
    //如果每页的item个数是24的话，要插入删除按钮图标
    if (count == 24) {
        
        for (int index = 0; index < array.count+1; index++) {
            
            //取余，24代表一页的总的cell数
            if ((index+1)%count == 0) {
                [sysEmoArr insertObject:@"Delete_ios7" atIndex:index];
                [sysKeyEmoArr insertObject:@"Delete_ios7" atIndex:index];
            }
            if (index == array.count && (index+1)%count != 0) {
                [sysEmoArr addObject:@"Delete_ios7"];
                [sysKeyEmoArr addObject:@"Delete_ios7"];
            }
        }
    }
    
    [emotionDic setValue:sysKeyEmoArr forKey:@"keyEmotion"];
    [emotionDic setValue:sysEmoArr forKey:@"emotion"];
    //计算每一组的页码数
    NSInteger sysCount = (sysEmoArr.count / count == 0) ? sysEmoArr.count / count : sysEmoArr.count / count+1;
    [emotionDic setValue:@(sysCount) forKey:@"pageCount"];
    
    return emotionDic;
}


+ (NSMutableAttributedString *)transferMessageString:(NSString *)text {

    //1、创建一个可变的属性字符串
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text];
    //2、通过正则表达式来匹配字符串
    
    NSString *regex_emoji = @"\\[[a-zA-Z0-9\\/\\u4e00-\\u9fa5]+\\]"; //匹配表情
    
    NSError *error = nil;
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:regex_emoji options:NSRegularExpressionCaseInsensitive error:&error];
    if (!re) {
        //        NSLog(@"%@", [error localizedDescription]);
        return attributeString;
    }
    
    NSArray *resultArray = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    //3、获取所有的表情以及位置
    //用来存放字典，字典中存储的是图片和图片对应的位置
    NSMutableArray *imageArray = [NSMutableArray arrayWithCapacity:resultArray.count];
    
    //根据匹配范围来用图片进行相应的替换
    for(NSTextCheckingResult *match in resultArray) {
        
        //获取数组元素中得到range
        NSRange range = [match range];
        //        //获取原字符串中对应的值
        NSString *subStr = [text substringWithRange:range];
        
        NSString *Path = [[NSBundle mainBundle] pathForResource:@"face" ofType:@"plist"];
        NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:Path];
        
        for (NSString *str in data.allKeys) {
            
            if ([str isEqualToString:subStr]) {
                
                //face[i][@"png"]就是我们要加载的图片
                //新建文字附件来存放我们的图片,iOS7才新加的对象
                NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
                //给附件添加图片
                textAttachment.image = [UIImage imageNamed:data[str]];
                
                //调整一下图片的位置,如果你的图片偏上或者偏下，调整一下bounds的y值即可
                textAttachment.bounds = CGRectMake(0, -4, 20, 20);
                //把附件转换成可变字符串，用于替换掉源字符串中的表情文字
                NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
                //把图片和图片对应的位置存入字典中
                NSMutableDictionary *imageDic = [NSMutableDictionary dictionaryWithCapacity:2];
                [imageDic setObject:imageStr forKey:@"image"];
                [imageDic setObject:[NSValue valueWithRange:range] forKey:@"range"];
                //把字典存入数组中
                [imageArray addObject:imageDic];
                
            }
        }
        
        
    }
    
    
    //4、从后往前替换，否则会引起位置问题
    for (int i = (int)imageArray.count -1; i >= 0; i--) {
        NSRange range;
        [imageArray[i][@"range"] getValue:&range];
        //进行替换
        [attributeString replaceCharactersInRange:range withAttributedString:imageArray[i][@"image"]];
    }
    return attributeString;
}

@end
